<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>后台管理</title>
    <link rel="icon" type="image/ico" href="pc/ico.png">
    <style>
        /* General Styles */

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Microsoft YaHei', '微软雅黑', sans-serif;
            background-color: #f5f5f5;
            color: #333;
            line-height: 1.6;
        }

        .header {
            background: linear-gradient(135deg, #ff4e50 0%, #f9d423 100%);
            color: white;
            padding: 2rem;
            text-align: center;
        }

        .header h1 {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .header p {
            font-size: 1rem;
            opacity: 0.9;
        }

        .menu-grid {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
            gap: 1rem;
            padding: 1rem;
            background-color: white;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .menu-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            text-decoration: none;
            color: #333;
            padding: 1rem;
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .menu-item:hover {
            background-color: #fff5e6;
            transform: translateY(-5px);
        }

        .menu-icon {
            font-size: 2rem;
            margin-bottom: 0.5rem;
        }

        .section {
            background-color: white;
            margin: 1rem;
            border-radius: 8px;
            overflow: hidden;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            padding: 1rem;
        }

        .section-header {
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem;
            background-color: #fff5e6;
            border-bottom: 1px solid #ffe0b2;
        }

        .section-title {
            font-size: 1.2rem;
            font-weight: bold;
            color: #ff4e50;
        }

        .table-container {
            overflow-x: auto;
            margin-top: 1rem;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            background-color: white;
        }

        table, th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: center;
        }

        table th {
            background-color: #ff4e50;
            color: white;
            font-weight: bold;
        }

        table tr:nth-child(even) {
            background-color: #f9f9f9;
        }

        .pagination-buttons {
            display: flex;
            justify-content: space-between;
            padding: 1rem;
        }

        .pagination-button {
            background-color: #ff4e50;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            cursor: pointer;
            border-radius: 5px;
            font-size: 0.9rem;
            display: inline-block;
            text-align: center;
        }

        .pagination-button:disabled {
            background-color: #ddd;
            cursor: not-allowed;
        }

        /* Modal Styles */

        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: #fff;
            padding: 1.5rem;
            border-radius: 8px;
            max-width: 400px;
            width: 90%;
            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
            text-align: center;
        }

        .modal-content h3 {
            margin-bottom: 1rem;
            font-size: 1.2rem;
            color: #ff4e50;
        }

        .modal-content button {
            background-color: #ff4e50;
            color: white;
            border: none;
            padding: 0.5rem 1rem;
            margin: 0.5rem;
            cursor: pointer;
            font-size: 1rem;
            border-radius: 5px;
            transition: background-color 0.3s;
        }

        .modal-content button:hover {
            background-color: #f43c42;
        }

        .modal-content .cancel-btn {
            background-color: #ccc;
            color: #333;
        }

        .modal-content .cancel-btn:hover {
            background-color: #b3b3b3;
        }

        .modal-content input, .modal-content textarea, .modal-content select {
            border: 1px solid #ddd;
            border-radius: 5px;
        }

        .modal-content input:focus, .modal-content textarea:focus, .modal-content select:focus {
            outline: none;
            border-color: #ff4e50;
            box-shadow: 0 0 5px rgba(255, 78, 80, 0.5);
        }

        .modal-content h3 {
            font-size: 1.5rem;
            color: #ff4e50;
            margin-bottom: 1rem;
        }

        /* Responsive Styles */

        @media (max-width: 768px) {
            /* Adjust the grid layout for smaller screens */
            .menu-grid {
                grid-template-columns: repeat(auto-fit, minmax(80px, 1fr));
            }

            /* Smaller font sizes for section headers */
            .section-title {
                font-size: 1rem;
            }

            /* Adjust modal content for mobile screens */
            .modal-content {
                padding: 1rem;
                max-width: 90%;
            }

            /* Make table scroll horizontally on smaller screens */
            .table-container {
                overflow-x: scroll;
            }

            /* Font adjustments for smaller screens */
            .header h1 {
                font-size: 1.5rem;
            }

            .header p {
                font-size: 0.9rem;
            }
        }

        @media (max-width: 480px) {
            /* For very small screens, reduce font and button sizes */
            .pagination-button {
                padding: 0.4rem 0.8rem;
                font-size: 0.8rem;
            }

            /* Further reduce header font sizes */
            .header h1 {
                font-size: 1.2rem;
            }

            .header p {
                font-size: 0.8rem;
            }

            .menu-icon {
                font-size: 1.5rem;
            }

            .section {
                padding: 0.5rem;
            }

            .modal-content h3 {
                font-size: 1.2rem;
            }
        }

    </style>
</head>
<body>

<header class="header">
    <h1>这个项目的后台管理</h1>
    <p>管理系统的各项内容</p>
</header>

<nav class="menu-grid">
    <a href="#" class="menu-item" onclick="showSection('user-management')">
        <span class="menu-icon">👤</span>
        <span>用户管理</span>
    </a>
    <a href="#" class="menu-item" onclick="showSection('file-management')">
        <span class="menu-icon">📁</span>
        <span>文件管理</span>
    </a>
    <a href="#" class="menu-item" onclick="showSection('log-management')">
        <span class="menu-icon">📜</span>
        <span>日志管理</span>
    </a>
    <a href="#" class="menu-item" onclick="showSection('announcement-management')">
        <span class="menu-icon">📢</span>
        <span>公告发布</span>
    </a>
    <a href="#" class="menu-item" onclick="showSection('post-management')">
        <span class="menu-icon">📝</span>
        <span>推文发布</span>
    </a>
    <a href="#" class="menu-item" onclick="showSection('exam-management')">
        <span class="menu-icon">🎓</span>
        <span>考试题目导入</span>
    </a>
</nav>

<section class="section" id="user-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">用户管理</h2>
        <button class="pagination-button" onclick="showAddUserModal()">修改权限</button>
    </div>
    <div class="table-container">
        <table>
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>姓名</th>
                <th>状态</th>
                <th>角色</th>
                <th>创建时间</th>
                <th>权限</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- User rows will be dynamically inserted here -->
            </tbody>
        </table>
    </div>
</section>


<section class="section" id="file-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">文件管理</h2>
    </div>
    <div class="table-container">
        <table>
            <thead>
            <tr>
                <th>文件ID</th>
                <th>文件名</th>
                <th>类型</th>
                <th>大小</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>1</td>
                <td>文件1.jpg</td>
                <td>图片</td>
                <td>1.2 MB</td>
                <td><button>下载</button> <button onclick="deleteFile(1)">删除</button></td>
            </tr>
            </tbody>
        </table>
    </div>
</section>

<section class="section" id="log-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">日志管理</h2>
    </div>
    <div class="table-container">
        <table>
            <thead>
            <tr>
                <th>日志ID</th>
                <th>用户ID</th>
                <th>登录时间</th>
                <th>IP地址</th>
                <th>登录地点</th>
                <th>操作结果</th>
            </tr>
            </thead>
            <tbody>
            <tr>
                <td>1</td>
                <td>101</td>
                <td>2023-10-15 14:35</td>
                <td>192.168.1.1</td>
                <td>成功</td>
            </tr>
            </tbody>
        </table>
    </div>
</section>

<section class="section" id="announcement-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">公告发布</h2>
        <button class="pagination-button" onclick="showAnnouncementModal()">发布公告</button>
    </div>
</section>

<section class="section" id="post-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">推文发布</h2>
        <button class="pagination-button" onclick="showPostModal()">发布推文</button>
    </div>
</section>

<section class="section" id="exam-management" style="display: none;">
    <div class="section-header">
        <h2 class="section-title">考试题目导入</h2>
        <button class="pagination-button" onclick="showExamModal()">导入题目</button>
    </div>

    <!-- Modal for Import Questions -->
    <div id="examModal" class="modal">
        <div class="modal-content">
            <h3>导入考试题目</h3>
            <input type="file" id="questionFile" accept=".xlsx, .xls" style="margin-bottom: 0.5rem;">
            <input type="text" id="subjectId" placeholder="输入科目ID" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem;">
            <button onclick="importQuestions()" style="width: 100%; padding: 0.5rem; font-size: 1rem; background-color: #ff4e50; color: white; border: none; cursor: pointer; border-radius: 5px;">导入</button>
            <button class="cancel-btn" onclick="closeModal('examModal')" style="width: 100%; padding: 0.5rem; margin-top: 0.5rem;">取消</button>
        </div>
    </div>
</section>


<!-- 模态框 -->
<!-- HTML Part for Enhanced Announcement Modal -->
<div id="announcementModal" class="modal">
    <div class="modal-content">
        <h3>发布公告</h3>
        <input type="text" id="announcementTitle" placeholder="公告标题" style="width: 100%; padding: 0.5rem; margin-bottom: 0.5rem;">
        <textarea id="announcementContent" placeholder="公告内容" style="width: 100%; height: 100px; padding: 0.5rem; margin-bottom: 0.5rem;"></textarea>
        <select id="announcementStatus" style="width: 100%; padding: 0.5rem; margin-bottom: 1rem;">
            <option value="发布中">发布中</option>
            <option value="草稿">草稿</option>
        </select>
        <button onclick="publishAnnouncement()" style="width: 100%; padding: 0.5rem; font-size: 1rem; background-color: #ff4e50; color: white; border: none; cursor: pointer; border-radius: 5px;">发布</button>
        <button class="cancel-btn" onclick="closeModal('announcementModal')" style="width: 100%; padding: 0.5rem; margin-top: 0.5rem;">取消</button>
    </div>
</div>

<div id="postModal" class="modal">
    <div class="modal-content">
        <h3>发布推文</h3>
        <textarea placeholder="推文内容"></textarea>
        <button onclick="publishPost()">发布</button>
        <button class="cancel-btn" onclick="closeModal('postModal')">取消</button>
    </div>
</div>


<script>


    async function publishAnnouncement() {
        const title = document.getElementById('announcementTitle').value;
        const content = document.getElementById('announcementContent').value;
        const status = document.getElementById('announcementStatus').value;

        // Data to be sent to the API
        const data = {
            title: title,
            content: content,
            status: status
        };

        try {
            const response = await fetch('/v1/announcements/add', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            });

            if (response.ok) {
                alert("公告已发布！");
                closeModal('announcementModal');
            } else {
                alert("公告发布失败，请重试。");
            }
        } catch (error) {
            console.error("Error:", error);
            alert("公告发布失败，请检查网络连接。");
        }
    }
    // Function to fetch and display all users
    async function fetchAllUsers() {
        try {
            const response = await fetch('/api/v1/users/getAllUsers', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    displayUsers(result.data); // Call displayUsers with the fetched data
                } else {
                    alert("获取用户数据失败：" + result.message);
                }
            } else {
                alert("请求失败，状态码：" + response.status);
            }
        } catch (error) {
            console.error("Error:", error);
            alert("获取用户数据时出错，请检查网络连接。");
        }
    }

    // Function to disable a user
    async function disableUser(userId) {
        try {
            const response = await fetch('/api/v1/users/passUser', {
                method: 'PUT',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: new URLSearchParams({ userId: userId }) // Send userId in the body
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    alert(result.message);
                } else {
                    alert("用户冻结失败：" + result.message);
                }
            } else {
                alert("请求失败，状态码：" + response.status);
            }
        } catch (error) {
            console.error("Error:", error);
            alert("用户冻结时出错，请检查网络连接。");
        }
    }


    // Function to display users in the table
    function displayUsers(users) {
        const userTableBody = document.querySelector('#user-management tbody');
        userTableBody.innerHTML = '';  // Clear any existing rows

        users.forEach(user => {
            const row = document.createElement('tr');

            row.innerHTML = `
            <td>${user.id}</td>
            <td>${user.username}</td>
            <td>${user.uname || '无'}</td>
            <td>${user.status === 0 ? '正常' : '禁用'}</td>
            <td>${user.roleName}</td>
            <td>${new Date(user.createdAt).toLocaleString()}</td>
            <td>${user.permissions.join(', ')}</td>
            <td>
                <button onclick="disableUser(${user.id})">冻结</button>
                <button onclick="deleteUser(${user.id})">删除</button>
            </td>
        `;

            userTableBody.appendChild(row);
        });
    }



    // Function to fetch and display all login logs
    async function fetchLoginLogs() {
        try {
            const response = await fetch('/api/v1/loginLog/getAll', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    displayLogs(result.data); // Call displayLogs with the fetched data
                } else {
                    alert("获取日志数据失败：" + result.message);
                }
            } else {
                alert("请求失败，状态码：" + response.status);
            }
        } catch (error) {
            console.error("Error:", error);
            alert("获取日志数据时出错，请检查网络连接。");
        }
    }

    // Function to display logs in the table
    function displayLogs(logs) {
        const logTableBody = document.querySelector('#log-management tbody');
        logTableBody.innerHTML = '';  // Clear any existing rows

        logs.forEach(log => {
            const row = document.createElement('tr');

            row.innerHTML = `
            <td>${log.id}</td>
            <td>${log.userId}</td>
            <td>${new Date(log.loginTime).toLocaleString()}</td>
            <td>${log.loginIp}</td>
            <td>${log.loginAddress}</td>
            <td>${log.loginResult}</td>
        `;

            logTableBody.appendChild(row);
        });
    }

    // Modify showSection to fetch logs when "日志管理" section is shown
    function showSection(sectionId) {
        // Hide all sections
        document.querySelectorAll('.section').forEach(section => section.style.display = 'none');
        // Show the selected section
        document.getElementById(sectionId).style.display = 'block';

        // Check if the "用户管理" or "日志管理" section is being opened, then fetch data
        if (sectionId === 'user-management') {
            fetchAllUsers(); // Fetch and display users for the user management section
        } else if (sectionId === 'log-management') {
            fetchLoginLogs(); // Fetch and display logs for the log management section
        }
    }

    // Function to handle the import of questions
    async function importQuestions() {
        const fileInput = document.getElementById('questionFile');
        const subjectIdInput = document.getElementById('subjectId');

        // Get the file and subjectId from the form
        const file = fileInput.files[0];
        const subjectId = subjectIdInput.value;

        if (!file || !subjectId) {
            alert("请上传文件并输入科目ID。");
            return;
        }

        // Create FormData to send file and subjectId
        const formData = new FormData();
        formData.append('file', file);
        formData.append('subjectId', subjectId);

        try {
            const response = await fetch('/api/v1/questions/excel/import', {
                method: 'POST',
                body: formData
            });

            if (response.ok) {
                const result = await response.json();
                if (result.code === 200) {
                    alert(result.message || "题目已成功导入！");
                    closeModal('examModal');
                } else {
                    alert("题目导入失败：" + result.message);
                }
            } else {
                alert("请求失败，状态码：" + response.status);
            }
        } catch (error) {
            console.error("Error:", error);
            alert("题目导入时出错，请检查网络连接。");
        }
    }

    function closeModal(modalId) {
        document.getElementById(modalId).style.display = 'none';
    }

    function showAnnouncementModal() {
        document.getElementById('announcementModal').style.display = 'flex';
    }

    function showPostModal() {
        window.location.href = `/blog.html`;
    }

    function showExamModal() {
        document.getElementById('examModal').style.display = 'flex';
    }


    function publishPost() {
        alert("推文已发布！");
        closeModal('postModal');
    }

</script>

</body>
</html>
